package com.playwright.xhs.auth;

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.LoadState;
import com.microsoft.playwright.options.WaitForSelectorState;
import com.playwright.util.zhihu2toutiao.PlaywrightUtils;

import java.nio.file.Paths;

/**
 * @author liyanhao
 * @Date 2024-06-03 20:11
 */
public class Login {

    /**
     * 1.命令行执行 "
     * 2.运行登录方法登录后保存登录信息
     * 3.登录后下次直接读取登录信息，并抓取数据
     *
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {

        try (Playwright playwright = Playwright.create()) {

            Browser browser = PlaywrightUtils.getBrowser(playwright);

            BrowserContext context = browser.newContext();
            Page page = context.newPage();
            page.navigate("https://www.xiaohongshu.com/explore");

            //判断是否登录完成
            page.waitForLoadState(LoadState.DOMCONTENTLOADED); // 等待页面完全加载
            String xpath = "//*[contains(text(), '登录后推荐更懂你的笔记')]";
            while (true) {
                if (page.waitForSelector(xpath, new Page.WaitForSelectorOptions().setState(WaitForSelectorState.ATTACHED).setTimeout(50000)).isVisible()) {
                    Thread.sleep(1000 * 5);
                    continue;
                }
                break;
            }
            //保存认证后的浏览器状态
            String statePath = Paths.get("D:\\IdeaProjects\\JavaTechnologyLearn\\_8106-playwright\\src\\main\\java\\com\\playwright\\xhs\\auth\\xhs_auth.json").toString();
            BrowserContext.StorageStateOptions options = new BrowserContext.StorageStateOptions();
            options.setPath(Paths.get(statePath));
            context.storageState(options);

            context.close();
            browser.close();
        }


    }
}
